package com.rocker.graduation.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
import org.springframework.web.util.WebUtils;

import com.rocker.graduation.constants.Constants;
import com.rocker.graduation.service.ICartService;
import com.rocker.graduation.service.IDistrictService;

@Controller
@RequestMapping("/district")
public class DistrictController {
	
	@Autowired
	private IDistrictService districtService;
	
	@Autowired
	private ICartService cartService;
	
	@RequestMapping("/getProvince.action")
	public ModelAndView getProvice(@RequestParam String cid, HttpServletRequest request){
		ModelAndView mav = new ModelAndView();
		Integer userId = (Integer) WebUtils.getSessionAttribute(request, Constants.USER_ID);
		MappingJackson2JsonView jsonView = new MappingJackson2JsonView();
		Map<String, Object> attributes = new HashMap<String, Object>();
		if (null == userId) {
			attributes.put(Constants.ERROR, Constants.ERROR_NULL_USER);
		}else {
			boolean isExisted = cartService.getCart(userId);
			if (isExisted) {
				attributes.put(Constants.SUCCESS, Constants.SUCCESS);
			}else {
				attributes.put(Constants.ERROR, Constants.ERROR_NULL_CART);
			}
		}
		
		String options = districtService.getDistrictById(cid);
		attributes.put("option", options);
		jsonView.setAttributesMap(attributes);
		mav.setView(jsonView);
		return mav;
	}
	
	@RequestMapping("/listProvince.action")
	public ModelAndView listProvince(@RequestParam String cid){
		ModelAndView mav = new ModelAndView();
		MappingJackson2JsonView jsonView = new MappingJackson2JsonView();
		Map<String, Object> attributes = new HashMap<String, Object>();
		String options = districtService.getStateById(cid);
		attributes.put("option", options);
		jsonView.setAttributesMap(attributes);
		mav.setView(jsonView);
		return mav; 
	}
	
	@RequestMapping("/listCity.action")
	public ModelAndView listCity(@RequestParam String cid){
		ModelAndView mav = new ModelAndView();
		MappingJackson2JsonView jsonView = new MappingJackson2JsonView();
		Map<String, Object> attributes = new HashMap<String, Object>();
		String options = districtService.getCityById(cid);
		attributes.put("option", options);
		jsonView.setAttributesMap(attributes);
		mav.setView(jsonView);
		return mav; 
	}
}
